from django.forms import models
from django.http import JsonResponse,HttpResponse

from apps.drf_test_0Django原始restful.models import BookinfoModels
from django.shortcuts import render

# Create your views here.
from django.views import View
from apps.drf_test_3重写Django原始restful.serializers import BookInfSerizlizer
import json
from rest_framework.response import Response

class BookInfoView(View):
    # 获取书籍
    def get(self,request):
        # 1、获取所有书籍
        books = BookinfoModels.objects.all()
        # 数据转换
        ser = BookInfSerizlizer(instance=books,many=True)
         # 返回响应
        return JsonResponse(ser.data,safe=False)

    # 新建书籍
    def post(self,request):

        # 1、获取参数
        res = json.loads(request.body.decode())

        print(res)
        # 2、校验参数

        # 3、数据入库
        try:
            serizlizer = BookInfSerizlizer(data=res)
            serizlizer.is_valid(raise_exception=True)
            res = serizlizer.save()
            print("保存后返回结果-----》",res)
            # return JsonResponse(res, status=201)
            return HttpResponse(res)
        except:
            print("【严重错误】")



class BookInfoDetailView(View):
    # 获取单个数据
    def get(self,request,pk):
        # 1、通过pk获取单本书籍
        book = BookinfoModels.objects.get(pk = pk)
        # 2、数据转换
        ser = BookInfSerizlizer(instance=book)
        # 3、返回数据
        return JsonResponse(ser.data)

    # 修改书籍
    def put(self,request,pk):
        # 1、获取更改后的数据
        dict_data = json.loads(request.body.decode())

        # 2、校验参数
        # 3、数据入库
        BookinfoModels.objects.filter(pk = pk).update(**dict_data)
        book = BookinfoModels.objects.get(pk=pk)
        # 4、数据转换
        ser = BookInfSerizlizer(instance=book)

        # 5、返回数据
        return JsonResponse(ser.data)

    # 删除书籍
    def delete(self,request,pk):
        # 1、获取书籍
        book = BookinfoModels.objects.get(id = pk)
        # 2、删除书籍
        book.delete()
        # 3、返回数据
        return HttpResponse("删除成功")
